﻿#include "SeqList.h"

//初始化
void SLInit(SL* ps) {
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}
//申请空间
void SLCheckCapacity(SL *ps) {
	//空间不够 申请空间 size和capacity一样大的时候
	if (ps->size == ps->capacity) {
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		//空间不够 2倍增容
		SLDataType *tmp = (SLDataType*)realloc(ps->arr, newCapacity * sizeof(SLDataType));
		if (tmp == NULL) {
			perror("realloc fail");
			exit(1);//直接退出程序，不在继续执行
		}
		//空间申请成功
		ps->arr = tmp;
		ps->capacity *= newCapacity;
	}
}
//尾插
void SLPushBack(SL *ps, SLDataType x) {
	//判断是否为空 方法一
	//if (ps == NULL) {
	//	return;
	//}
	//方法二 断言
	//真 通过 假 报错
	assert(ps != NULL);
	SLCheckCapacity(ps);
	ps->arr[ps->size++] = x;
}
//尾删
void SLPopBack(SL *ps) {
	assert(ps != NULL && ps->size);
	ps->size--;
}
//头插
void SLPushFront(SL* ps, SLDataType x) {
	assert(ps != NULL);
	SLCheckCapacity(ps);
	//先让顺序表中已有的数据向后挪动一位 
	for (int i = ps->size; i > 0; i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}
//头删
void SLPopFront(SL *ps) {
	assert(ps != NULL);
	for (int i = 0; i < ps->size-1; i++) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}
//打印顺序表
void SLPrint(SL s) {
	for (int i = 0; i < s.size; i++) {
		printf("%d ", s.arr[i]);
	}
	printf("\n");
}
//查找
int SLFind(SL* ps, SLDataType x) {
	for (int i = 0; i < ps->size; i++) {
		if (ps->arr[i] == x) {
			//找到了返回有效下标
			return i;
		}
		//没找到 返回无效下标
		return -1;
	}
}
//指定位置之前插⼊数据
void SLInsert(SL* ps, int pos, SLDataType x) {
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	for (int i = ps->size; i > pos; i--) {
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}
//删除指定位置数据
void SLErase(SL* ps, int pos) {
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	for (int i = pos; i > ps->size-1; i++) {
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}